require 'google/api_client'
require_relative 'drive_functions'
require_relative 'spreadsheet'

@emails ||= Spreadsheet.new("Emails.xlsx")

puts "Initializing Client"
api_client = Google::APIClient.new()
drive = api_client.discovered_api('drive', 'v2')

SERVICE_ACCOUNT_ID = '952633392694-tu4inan45u93a590veea177i7dn61039@developer.gserviceaccount.com'
KEY_FILE = 'C:\Users\klink\Downloads\3d7c16ee3b207ee2190c2715a2d26c0c015dc416-privatekey.p12'
KEY_SECRET = 'notasecret'
FILE = 'report.html'

puts "Loading Credentials"
key = Google::APIClient::PKCS12.load_key(KEY_FILE, KEY_SECRET)
asserter = Google::APIClient::JWTAsserter.new(
  SERVICE_ACCOUNT_ID,
  'https://www.googleapis.com/auth/drive',
  key)

puts "Authorizing"
api_client.authorization = asserter.authorize()


#################################################################################
#Uploads a file to the google drive service account
puts "Uploading File"
file = drive.files.insert.request_schema.new({
                                                 'title' => "NeweggAutomationResults: #{Time.now}",
                                                 'description' => 'A test document',
                                                 'mimeType' => 'text/html'
                                             })
media = Google::APIClient::UploadIO.new('C:\RubyProjects\neweggauto\newegg-cucumber-automation\report.html', 'text/html')

result = api_client.execute(
  :api_method => drive.files.insert,
  :body_object => file,
  :media => media,
  :parameters => {
    'uploadType' => 'multipart',
    'alt' => 'json'})

#j result.data

########################################################
#Stores the IDs of all the files on the drive to an array
puts "Loading IDs of files on Google Drive"
list = retrieve_all_files(api_client)
FILE_ID = Array.new
list.each do |num|
  FILE_ID.push(num.id.to_s)
end
#############################################################
#Adds permission to the last file to be uploaded to be shared with another user
puts "Adding permissions to email accounts:"
@list = @emails.getColumn(1)
for i in 0..(@list.size - 1)
  puts @list[i]
  insert_permission(api_client, FILE_ID.first, @list[i], 'user', 'writer')
end